package cn.linjianhui.article.utils;

import cn.linjianhui.article.model.PageData;
import cn.linjianhui.article.model.PageQuery;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

public class PageUtil {
    public static <T> PageData<T> toPageData(IPage<T> page) {
        if (page == null) {
            return null;
        } else {
            PageData<T> pagination = new PageData<>();
            pagination.setCurrent(page.getCurrent());
            List<T> list = page.getRecords();
            if (list != null) {
                pagination.setResults(new ArrayList<>(list));
            }

            pagination.setSize(page.getSize());
            pagination.setTotal(page.getTotal());
            return pagination;
        }
    }

    public static <T> IPage<T> fromPageQuery(PageQuery pageQuery) {
        return new Page<>(pageQuery.getCurrent(), pageQuery.getSize());
    }

    public static <T> PageData<T> mapToPageData(IPage<?> page, Class<T> tClass) {
        if(page == null) {
            return null;
        } else {
            List<T> result = new ArrayList<>();
            PageData<T> pagination = new PageData<>();
            pagination.setCurrent(page.getCurrent());
            for(Object item : page.getRecords()) {
                T obj = MapUtil.mapToObj(item, tClass);
                if(obj != null) {
                    result.add(obj);
                }
            }
            pagination.setResults(result);
            pagination.setSize(page.getSize());
            pagination.setTotal(page.getTotal());
            return pagination;
        }
    }
}
